package control;

import model.Model;
import view.GameFrame;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import static model.Model.*;
import static view.GameFrame.step;
import static model.Model.images;
import static model.Model.num;
import static model.Model.choose;
public class KeyAction implements KeyListener {
    Model model;
    GameFrame gameFrame;

    public KeyAction(GameFrame gameFrame,Model model) {
        this.gameFrame = gameFrame;
        this.model=model;
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    //键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
        //按住W建,则一键通关
        if (e.getKeyCode() == 65) {
            String path = images + choose + num;
            //清空之前的图片
            gameFrame.getContentPane().removeAll();
            //记录步数
            gameFrame.addStep();
            //创建全图的标签
            JLabel all = new JLabel(new ImageIcon(path + "all.jpg"));
            //设置全图标签的位置和大小
            all.setBounds(83, 134, 420, 420);
            //将全图放进窗体
            gameFrame.getContentPane().add(all);
            //重新加载背景图片
            gameFrame.addBackground();
            //刷新一下
            gameFrame.repaint();
        }
    }

    //键盘监听
    @Override
    public void keyReleased(KeyEvent e) {
        if (victory) {
            return;
        }
        //获取用户的按键,来移动键盘
        switch (e.getKeyCode()) {
            //向左移
            case 37 -> {
                if (y < 3) {
                    data[x][y] = data[x][y + 1];
                    data[x][y + 1] = 0;
                    y++;
                    step++;
                }
            }
            //向上移
            case 38 -> {
                if (x < 3) {
                    data[x][y] = data[x + 1][y];
                    data[x + 1][y] = 0;
                    x++;
                    step++;
                }
            }
            //向右移
            case 39 -> {
                if (y > 0) {
                    data[x][y] = data[x][y - 1];
                    data[x][y - 1] = 0;
                    y--;
                    step++;
                }
            }
            //向下移
            case 40 -> {
                if (x > 0) {
                    data[x][y] = data[x - 1][y];
                    data[x - 1][y] = 0;
                    x--;
                    step++;
                }
            }
            //按住A键出现去全图
            case 87 -> {
                data = new int[][]{
                        {1, 2, 3, 4},
                        {5, 6, 7, 8},
                        {9, 10, 11, 12},
                        {13, 14, 15, 0}
                };
                victory = true;
            }
        }
        //判断是否胜利
        model.isVictory();
        //重新加载图片
        gameFrame.initImg();
    }

}
